import api from '@/core/Api'

export default {
  data () {
    return {
      maxsize: 0.6, // 图片最大质量1M
      maxWH: 1000 // 图片最大宽或高
    }
  },
  methods: {
    async imgCompressAsFile (url, file) {
      const dataURL = await this.imgCompress(url, file)
      let blob = api.dataURLtoBlob(dataURL)
      return api.blobToFile(blob, file.name)
    },
    /**
     * 压缩图片
     * 如果不压缩，图片太大时，vuex state 通过 vuex-persistedstate 持久化的时候会导致文件太大
     */
    imgCompress (url, file) { // path是指上传的图片，obj是压缩的品质，越低越模糊
      // 这里的this 是把vue的实例对象指向改变为_this
      const _this = this
      return new Promise((resolve) => {
        const img = new Image()
        img.onload = function () {
          if (this.width <= _this.maxWH && this.height <= _this.maxWH && file.size / 1024 / 1024 < _this.maxsize) {
            resolve(url)
            return
          }

          if (this.width > _this.maxWH || this.height > _this.maxWH) {
            if (this.width / this.height > 1) {
              this.height = Math.round(_this.maxWH / this.width * this.height)
              this.width = _this.maxWH
            } else {
              this.width = Math.round(_this.maxWH / this.height * this.width)
              this.height = _this.maxWH
            }
          }
          resolve(_this.scaleimg(this, file.type))
        }
        img.src = url
      })
    },
    /**
     * maxsize 设置压缩后的最大值
     */
    scaleimg (img, type) {
      let height = img.height
      let width = img.width
      let can = document.createElement('canvas')
      can.height = height
      can.width = width
      let casimg = can.getContext('2d')
      casimg.clearRect(0, 0, width, height)
      casimg.drawImage(img, 0, 0, width, height)
      let base64data = can.toDataURL(type) // 获取在canvas元素中的图片截图base64编码
      let size = api.convertBase64UrlToBlob(base64data).size
      size = Math.round(size / 1024 / 1024) // 获取压缩前的图片大小
      if (size > this.maxsize) {
        return can.toDataURL(type, this.maxsize / size)
      }
      return base64data
    }
  }
}
